package test;

import java.util.ArrayList;
import java.util.List;

public class CalculaterTask implements Runnable {
    private final int startIndex;
    private final int endIndex;
    private final int[] results;
    private final int index;


    public CalculaterTask(int startIndex, int endIndex, int[] results, int index) {
        this.startIndex = startIndex;
        this.endIndex = endIndex;
        this.results = results;
        this.index = index;
    }

    @Override
    public void run() {
        int count = 0;
        label: for (int i=startIndex; i<=endIndex-1; i++) {
            if (i == 0 || i == 1) continue;
            for (int j=2; j<=Math.sqrt(i); j++) {
                if (i % j == 0) {
                    continue label;
                }
            }
            count++;
        }
        results[index] = count;
    }
}

class ParallerGroupCalculater {
    public static int calc(int n) {
        List<Thread> threads = new ArrayList<>();
        int numThreads = Runtime.getRuntime().availableProcessors();

        int[] results = new int[numThreads];

        int startIndex, endIndex, step;
        step = n / numThreads;
        startIndex = 0;
        endIndex = step;
        for (int i=0; i<numThreads; i++) {
            CalculaterTask task=new CalculaterTask(startIndex, endIndex, results, i);
            Thread thread=new Thread(task);
            thread.start();
            threads.add(thread);
//            System.out.println("start=" + startIndex + ", end=" + endIndex);
            startIndex = endIndex;
            endIndex = i == numThreads-2 ? n:endIndex + step;
        }

        for (Thread thread: threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        int s = 0;
        for (int r: results) {
            s += r;
        }
        return s;
    }

}
